/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.paymentexpress.server;

import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import net.oauth.jsontoken.crypto.HmacSHA256Verifier;
import net.oauth.jsontoken.crypto.SignatureAlgorithm;
import net.oauth.jsontoken.crypto.Verifier;
import net.oauth.jsontoken.discovery.VerifierProvider;
import net.oauth.jsontoken.discovery.VerifierProviders;

import com.google.common.collect.Lists;
import com.google.paymentexpress.jwt.FullWalletResponse;
import com.google.paymentexpress.jwt.IgnoreAudience;
import com.google.paymentexpress.jwt.TransactionStatusNotification;
import com.google.paymentexpress.server.beans.Order;
import com.google.paymentexpress.server.config.Config;
import com.google.paymentexpress.server.config.TestCards;
import com.google.paymentexpress.server.decrypt.Decrypter;

/**
 * This servlet handles the Full Wallet Response JWT and decrypts the encrypted 
 * card number + cvv using the decrypter class.
 * 
 * Velocity Templates are used for rendering the receipt page.
 * 
 * @author pying(peng ying)
 *
 */
public class ReceiptServlet extends HttpServlet {

  
  private final String BAD_CVC = "Bad CVV value entered";
  
  /**
   * 
   */
  private static final long serialVersionUID = 1L;
  
  /**
   * Post pulls post body data and renders the receipt content
   */
  public void doPost(HttpServletRequest req, HttpServletResponse resp){
    
    String origin = Config.getDomain(req);
    
    //Get post params
    String wallet = req.getParameter("fullWalletJWT");
    String drink = req.getParameter("orderDescription");
    String total = req.getParameter("formTotal");
    
    Order order = new Order(drink, total);
    
    //Parse JWT to get body data
    try {
      final Verifier hmacVerifier = new HmacSHA256Verifier(Config.MERCHANT_SECRET.getBytes());
      VerifierProvider hmacLocator = new VerifierProvider() {
        
        public List<Verifier> findVerifier(String id, String key){
          return Lists.newArrayList(hmacVerifier);
        }

      };
      
      VerifierProviders locators = new VerifierProviders();
      locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator); 
      
      JsonTokenParser parser = new JsonTokenParser(locators, new IgnoreAudience());
      JsonToken jwt = parser.deserialize(wallet);
      
      //Convert JsonToken to Java Objects
      FullWalletResponse fwr = new FullWalletResponse(jwt);
      
      //Decrypt Card Number and CVV
      Decrypter decryptor = new Decrypter();
      String cardNumber = decryptor.decrypt(fwr.getSelection().getPay().getPayment_instrument().getFull_cart_number());
      String cardCvv = decryptor.decrypt(fwr.getSelection().getPay().getPayment_instrument().getCvc());
      
      Boolean badCard = TestCards.checkCard(cardNumber);
      TransactionStatusNotification status = null;
      if (badCard){
        status = new TransactionStatusNotification(Config.MERCHANT_ID, Config.MERCHANT_SECRET, fwr.getGoogle_transaction_id(), TransactionStatusNotification.stat.FAILURE, TransactionStatusNotification.reas.BAD_CVC, BAD_CVC);
      } else {
        status = new TransactionStatusNotification(Config.MERCHANT_ID, Config.MERCHANT_SECRET, fwr.getGoogle_transaction_id(), TransactionStatusNotification.stat.SUCCESS);
      }
      status.setOrigin(origin);
      
      //Initiate Velocity and define context
      Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute");
      
      // Escape HTML
      Velocity.setProperty("eventhandler.referenceinsertion.class", "org.apache.velocity.app.event.implement.EscapeHtmlReference");
      Velocity.setProperty("eventhandler.escape.html.match", "/.*/");
      
      Velocity.init();

      VelocityContext context = new VelocityContext();
      context.put("pay", fwr.getSelection().getPay());
      context.put("ship", fwr.getSelection().getShip());
      context.put("cardnumber", cardNumber);
      context.put("cvv", cardCvv);
      context.put("order", order);
      context.put("status", status.generateJWT());
      context.put("walletJSUrl", Config.WALLET_JS_URL);
      context.put("domain", origin);
      
      if (badCard){
        context.put("message", "Sorry, your order has Failed! Please update your CVV.");
      }
      else {
        context.put("message", "Your order has been placed!  Thank you for your order.");
      }
      
      //Return page to client
      PrintWriter pw;
      pw = resp.getWriter();
      Velocity.mergeTemplate("receipt.vm","UTF-8", context, pw);
      pw.flush();
      pw.close();
      
    } catch (InvalidKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ResourceNotFoundException e) {
      e.printStackTrace();
    } catch (ParseErrorException e) {
      e.printStackTrace();
    } catch (MethodInvocationException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  } 
}
